package com.ars.common.dao;

import com.ars.common.beans.Active.Active;
import com.ars.common.utils.DBUtil;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

// 发布活动，写入数据库
public class addActiveMysql {
    public static void addActive(Active active) throws Exception {
        String sql = "INSERT INTO active(name, creatorID, beginTime, endTime, type, createTime) VALUES (?, ?, ?, ?, ?, ?)";
        String sql2 = "SELECT id FROM active WHERE name = ? and creatorID = ? and createTime = ?";

        // 定义用于转换的时间格式
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");

        // 将字符串时间转换为Timestamp
        Date timeBeginDate = dateTimeFormat.parse(active.getBeginTime());
        Timestamp beginTimestamp = new Timestamp(timeBeginDate.getTime());

        Date timeEndDate = dateTimeFormat.parse(active.getEndTime());
        Timestamp endTimestamp = new Timestamp(timeEndDate.getTime());

        // 获取当前时间，并转换为Timestamp
        Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());

        // 获取数据库连接
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
             PreparedStatement ps2 = conn.prepareStatement(sql2)) {

            // 设置PreparedStatement参数
            ps.setString(1, active.getName());
            ps.setString(2, active.getCreatorID());
            ps.setTimestamp(3, beginTimestamp);
            ps.setTimestamp(4, endTimestamp);
            ps.setString(5, active.getType());
            ps.setTimestamp(6, currentTimestamp);

            // 执行插入操作
            ps.executeUpdate();

            // Retrieve the generated ID using generated keys
            ResultSet generatedKeys = ps.getGeneratedKeys();
            if (generatedKeys.next()) {
                int id = generatedKeys.getInt(1);
                String idFile = "src\\main\\webapp\\images\\" + id + "\\";
                System.out.println("创建活动成功，活动ID为：" + id);
                System.out.println("创建活动成功，活动ID文件为：" + idFile);
                //生成对应的文件名
                new File(idFile).mkdirs();
                System.out.println("创建活动成功，活动ID文件创建成功");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            throw new Exception("Error occurred while adding activity to the database.");
        }
    }
}
